// Copyright 2024 Xiguan Inc
// Author: xiguan
// Email: xiguan.teng@qq.com
// Created on 2024/8/8
// This is ...
//

#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <client.grpc.pb.h>
#include <client.pb.h>
#include <grpcpp/grpcpp.h>

#include <filesystem>

ABSL_FLAG(std::string, target, "localhost:23202", "Server address");

class Client {
 public:
  Client(std::shared_ptr<grpc::Channel> channel)
      : stub_(mapreduce_client::CountWords::NewStub(channel)){};

  mapreduce_client::ClientReply get_files_word_cnt(
      mapreduce_client::ClientRequest &request) {
    grpc::ClientContext           client_context;
    mapreduce_client::ClientReply client_reply;
    grpc::Status                  status =
        stub_->count_files_words(&client_context, request, &client_reply);

    if (status.ok()) {
      return client_reply;
    } else {
      std::cout << status.error_code() << ": " << status.error_message()
                << std::endl;
      return client_reply;
    }
  }

 private:
  std::unique_ptr<mapreduce_client::CountWords::Stub> stub_;
};

int main(int argc, char *argv[]) {
  if (argc < 2) {
    std::cout << "Usage: " << argv[0] << " input files.." << std::endl;
  }

  std::string target_str = absl::GetFlag(FLAGS_target);

  std::string current_path = std::getenv("PWD");
  current_path += '/';

  mapreduce_client::ClientRequest client_request;
  for (int idx = 1; idx < argc; ++idx) {
    auto abs_path = current_path + argv[idx];
    client_request.add_files(abs_path);
  }
  Client client(
      grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  auto ret = client.get_files_word_cnt(client_request);
  int  len = ret.outfile_size();
  for (int idx = 0; idx < len; ++idx) {
    std::cout << "outfile: " << ret.outfile(idx) << std::endl;
  }
  return 0;
}